package cn.bluech.lib.utils;

import android.text.TextUtils;

import java.util.Collection;
import java.util.List;

/**
 * Description:
 * Created by Codeant on 2019/6/3.
 */
public class ListUtils {
    public static boolean isEmpty(Collection<?> collection){
        return ((null==collection)||(collection.isEmpty()));
    }

    public static <T> T getLast(List<T> list){
        return isEmpty(list)?null:list.get(list.size()-1);
    }


    public static String join(Collection<?> collection, String separator, Flat<Object> flat){
        if(null==flat)
            return join(collection,separator);

        if(isEmpty(collection))
            return "";

        StringBuilder sb  = new StringBuilder();
        for(Object element : collection){
            String str = flat.toString(element);
            if(null==str)
                continue;
            sb.append(str);
            if(!TextUtils.isEmpty(separator))
                sb.append(separator);
        }
        if((sb.length()>0)&&(!TextUtils.isEmpty(separator))){
            return sb.substring(0,sb.length()-separator.length());
        }

        return sb.toString();
    }

    public static String join(Collection<?> collection, String separator){
        return join(collection, separator, element -> {
            if(null==element)
                return "null";
            else if(element instanceof String)
                return (String) element;
            else
                return element.toString();
        });
    }


    public interface Flat<T>{
        String toString(T element);
    }
}
